package com.tanhua.service;

import cn.hutool.captcha.CaptchaUtil;
import cn.hutool.captcha.LineCaptcha;
import cn.hutool.core.util.StrUtil;
import cn.hutool.crypto.SecureUtil;
import com.alibaba.fastjson.JSON;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.tanhua.domain.Admin;
import com.tanhua.exception.BusinessException;
import com.tanhua.interceptor.AdminHolder;
import com.tanhua.mapper.AdminMapper;
import com.tanhua.utils.JwtUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Service;

import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.TimeUnit;

@Service
public class AdminService {

    @Autowired
    private StringRedisTemplate stringRedisTemplate;
    @Autowired
    private AdminMapper adminMapper;


    // 根据token从redis中获取用户
    public Admin tokenfromUser(String token) {
        String json = stringRedisTemplate.opsForValue().get("manager_token_" + token);
        //将json转换成对象
        Admin admin = JSON.parseObject(json, Admin.class);
        //追加一天
        stringRedisTemplate.opsForValue().set("manager_token_"+token,json,1, TimeUnit.DAYS);
        return admin;
    }

    //生成验证码
    public ResponseEntity verification(String uuid, HttpServletResponse response) throws IOException {
        // 1 制作验证码
        LineCaptcha lineCaptcha = CaptchaUtil.createLineCaptcha(300, 100);//设置长和宽
        // 2 获取验证码内容
        String yzm_code = lineCaptcha.getCode();
        // 3 存入到redis
        stringRedisTemplate.opsForValue().set("manager_code_"+uuid,yzm_code,5, TimeUnit.MINUTES);
        //4 向浏览器返回验证码
        lineCaptcha.write(response.getOutputStream());

        return ResponseEntity.ok(null);
    }

    //登录
    public ResponseEntity login(String username, String password, String verificationCode, String uuid) {

        //1 判断验证码是否为空
        if(StrUtil.isEmpty(verificationCode) || StrUtil.isEmpty(uuid)){
            throw  new BusinessException("验证码不能为空");
        }
        //2 判断用户名和密码是否为空
        if(StrUtil.isEmpty(username) || StrUtil.isEmpty(password)){
            throw  new BusinessException("用户名或密码为空");
        }
        //3 判断验证码和redis对比是否正确
        String redisCode = stringRedisTemplate.opsForValue().get("manager_code_" + uuid);
        if(StrUtil.isEmpty(redisCode) || !verificationCode.equals(redisCode)){
            throw  new BusinessException("验证码错误");
        }
        //4 根据账号名查数据库用户(条件查)
        QueryWrapper<Admin> qw = new QueryWrapper<>();
        qw.eq("username",username);
        Admin admin = adminMapper.selectOne(qw);
        //5 判断用户是否为空
        if(admin==null){
            throw  new BusinessException("此用户不存在");
        }
        //6 在获取页面的密码进行md5加密和查询出来的对象密码做对比
        if(!admin.getPassword().equals(SecureUtil.md5(password))){
            throw  new BusinessException("密码错误");
        }
        //7 一致：登录成功 清除redis验证码
        stringRedisTemplate.delete("manager_code_" + uuid);

        // 8 通过jwt将当前用户生成token
        String token = JwtUtil.createToken(admin.getUsername(), admin.getId(), "tanhua-manager");
        // 9 token当key  admin对象当value存入到redis
        String admin_json = JSON.toJSONString(admin);
        stringRedisTemplate.opsForValue().set("manager_token_"+token,admin_json,24,TimeUnit.HOURS);
        //10 token返回
        Map resultMap=new HashMap();
        resultMap.put("token",token);
        return ResponseEntity.ok(resultMap);
    }

    //根据对应的token将redis中的对象给删除了
    public ResponseEntity logout() {
        Admin admin = AdminHolder.getAdmin();
        stringRedisTemplate.delete("manager_token_"+admin.getToken());
        return ResponseEntity.ok(null);
    }
}
